package com.agrimall.service.impl;

import com.agrimall.entity.Cart;
import com.agrimall.entity.Order;
import com.agrimall.entity.OrderItem;
import com.agrimall.entity.Product;
import com.agrimall.mapper.CartMapper;
import com.agrimall.mapper.OrderItemMapper;
import com.agrimall.mapper.OrderMapper;
import com.agrimall.mapper.ProductMapper;
import com.agrimall.service.CartService;
import com.agrimall.service.ProductService;
import com.agrimall.service.UserService;
import com.agrimall.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车服务实现类
 */
public class CartServiceImpl implements CartService {
    
    @Override
    public boolean addToCart(Long userId, Long productId, Integer quantity) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
            ProductService productService = new ProductServiceImpl();
            
            // 查询商品信息
            Product product = productService.getProductById(productId);
            if (product == null) {
                System.out.println("购物车添加失败：商品不存在，productId=" + productId);
                return false; // 商品不存在
            }
            
            // 检查商品状态（status为null或0表示下架）
            if (product.getStatus() == null || product.getStatus() == 0) {
                System.out.println("购物车添加失败：商品已下架，productId=" + productId + ", status=" + product.getStatus());
                return false; // 商品已下架
            }
            
            // 检查商户ID
            if (product.getMerchantId() == null) {
                System.out.println("购物车添加失败：商品商户ID为空，productId=" + productId);
                return false;
            }
            
            // 检查库存（stock为null时视为0）
            Integer stock = product.getStock();
            if (stock == null) {
                stock = 0;
            }
            if (stock < quantity) {
                System.out.println("购物车添加失败：库存不足，productId=" + productId + ", stock=" + stock + ", quantity=" + quantity);
                return false; // 库存不足
            }
            
            // 检查购物车中是否已存在该商品
            Cart existingCart = cartMapper.selectByUserIdAndProductId(userId, productId);
            if (existingCart != null) {
                // 已存在，更新数量
                int newQuantity = existingCart.getQuantity() + quantity;
                if (stock < newQuantity) {
                    System.out.println("购物车添加失败：库存不足（已有商品），productId=" + productId + ", stock=" + stock + ", existingQuantity=" + existingCart.getQuantity() + ", addQuantity=" + quantity);
                    return false; // 库存不足
                }
                existingCart.setQuantity(newQuantity);
                int result = cartMapper.update(existingCart);
                sqlSession.commit();
                if (result > 0) {
                    System.out.println("购物车更新成功：productId=" + productId + ", userId=" + userId + ", newQuantity=" + newQuantity);
                } else {
                    System.out.println("购物车更新失败：数据库更新失败，cartId=" + existingCart.getCartId());
                }
                return result > 0;
            } else {
                // 不存在，新增
                Cart cart = new Cart();
                cart.setUserId(userId);
                cart.setProductId(productId);
                cart.setMerchantId(product.getMerchantId());
                cart.setQuantity(quantity);
                
                try {
                    int result = cartMapper.insert(cart);
                    sqlSession.commit();
                    if (result > 0) {
                        System.out.println("购物车添加成功：productId=" + productId + ", userId=" + userId + ", quantity=" + quantity + ", cartId=" + cart.getCartId());
                    } else {
                        System.out.println("购物车添加失败：数据库插入失败，productId=" + productId + ", 返回结果=" + result);
                    }
                    return result > 0;
                } catch (Exception insertEx) {
                    System.err.println("购物车插入异常：productId=" + productId + ", userId=" + userId + ", merchantId=" + product.getMerchantId());
                    insertEx.printStackTrace();
                    sqlSession.rollback();
                    throw insertEx;
                }
            }
        } catch (Exception e) {
            sqlSession.rollback();
            System.err.println("购物车添加异常：productId=" + productId + ", userId=" + userId);
            e.printStackTrace();
            return false;
        } finally {
            sqlSession.close();
        }
    }
    
    @Override
    public boolean updateQuantity(Long cartId, Integer quantity) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
            ProductService productService = new ProductServiceImpl();
            
            // 查询购物车项
            Cart cart = cartMapper.selectById(cartId);
            if (cart == null) {
                return false;
            }
            
            // 查询商品信息
            Product product = productService.getProductById(cart.getProductId());
            if (product == null || product.getStatus() == 0) {
                return false; // 商品不存在或已下架
            }
            
            // 检查库存
            if (product.getStock() < quantity) {
                return false; // 库存不足
            }
            
            // 更新数量
            cart.setQuantity(quantity);
            int result = cartMapper.update(cart);
            sqlSession.commit();
            return result > 0;
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            return false;
        } finally {
            sqlSession.close();
        }
    }
    
    @Override
    public boolean removeFromCart(Long cartId) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
            int result = cartMapper.delete(cartId);
            sqlSession.commit();
            return result > 0;
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            return false;
        } finally {
            sqlSession.close();
        }
    }
    
    @Override
    public boolean clearCart(Long userId) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
            int result = cartMapper.deleteByUserId(userId);
            sqlSession.commit();
            return result > 0;
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            return false;
        } finally {
            sqlSession.close();
        }
    }
    
    @Override
    public List<Cart> getCartList(Long userId) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
            return cartMapper.selectByUserId(userId);
        } finally {
            sqlSession.close();
        }
    }
    
    @Override
    public int getCartCount(Long userId) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
            Integer count = cartMapper.countByUserId(userId);
            return count != null ? count : 0;
        } finally {
            sqlSession.close();
        }
    }
    
    @Override
    public boolean batchCreateOrders(Long userId, List<Long> cartIds, String deliveryAddress, String receiverName, String receiverPhone, String paymentMethod) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
            OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
            OrderItemMapper itemMapper = sqlSession.getMapper(OrderItemMapper.class);
            ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
            UserService userService = new UserServiceImpl();
            
            // 查询选中的购物车项
            List<Cart> selectedCarts = new ArrayList<>();
            BigDecimal totalAmount = BigDecimal.ZERO;
            Map<Long, Product> productMap = new HashMap<>(); // 缓存商品信息
            
            for (Long cartId : cartIds) {
                Cart cart = cartMapper.selectById(cartId);
                if (cart != null && cart.getUserId().equals(userId)) {
                    Product product = productMapper.selectById(cart.getProductId());
                    if (product != null && product.getStatus() != null && product.getStatus() == 1) {
                        Integer stock = product.getStock() != null ? product.getStock() : 0;
                        if (stock >= cart.getQuantity()) {
                            selectedCarts.add(cart);
                            productMap.put(cart.getProductId(), product);
                            BigDecimal subtotal = product.getPrice().multiply(new BigDecimal(cart.getQuantity()));
                            totalAmount = totalAmount.add(subtotal);
                        }
                    }
                }
            }
            
            if (selectedCarts.isEmpty()) {
                return false;
            }
            
            // 检查用户余额
            com.agrimall.entity.User user = userService.getUserById(userId);
            if (user == null || user.getBalance() == null || user.getBalance().compareTo(totalAmount) < 0) {
                return false; // 余额不足
            }
            
            // 按商户分组
            Map<Long, List<Cart>> merchantCartsMap = new HashMap<>();
            for (Cart cart : selectedCarts) {
                Long merchantId = cart.getMerchantId();
                merchantCartsMap.computeIfAbsent(merchantId, k -> new ArrayList<>()).add(cart);
            }
            
            // 扣减用户余额（先扣余额，避免订单创建后余额不足）
            boolean deductSuccess = userService.deductBalance(userId, totalAmount);
            if (!deductSuccess) {
                return false;
            }
            
            // 为每个商户创建订单
            List<String> orderNos = new ArrayList<>();
            for (Map.Entry<Long, List<Cart>> entry : merchantCartsMap.entrySet()) {
                Long merchantId = entry.getKey();
                List<Cart> merchantCarts = entry.getValue();
                
                // 计算该商户订单总金额
                BigDecimal merchantTotal = BigDecimal.ZERO;
                List<OrderItem> orderItems = new ArrayList<>();
                for (Cart cart : merchantCarts) {
                    Product product = productMap.get(cart.getProductId());
                    BigDecimal subtotal = product.getPrice().multiply(new BigDecimal(cart.getQuantity()));
                    merchantTotal = merchantTotal.add(subtotal);
                    
                    OrderItem item = new OrderItem();
                    item.setProductId(cart.getProductId());
                    item.setProductName(product.getProductName());
                    item.setProductImage(product.getImageUrl());
                    item.setPrice(product.getPrice());
                    item.setQuantity(cart.getQuantity());
                    item.setSubtotal(subtotal);
                    orderItems.add(item);
                }
                
                // 创建订单
                Order order = new Order();
                order.setUserId(userId);
                order.setMerchantId(merchantId);
                order.setTotalAmount(merchantTotal);
                order.setStatus(1); // 直接设为待发货（因为已经扣了余额）
                order.setPaymentMethod(paymentMethod != null ? paymentMethod : "余额支付");
                order.setPaymentTime(new java.util.Date());
                order.setDeliveryAddress(deliveryAddress);
                order.setReceiverName(receiverName);
                order.setReceiverPhone(receiverPhone);
                
                // 生成订单编号
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
                String orderNo = "ORD" + sdf.format(new java.util.Date()) + (int)(Math.random() * 1000);
                order.setOrderNo(orderNo);
                
                // 插入订单
                int orderResult = orderMapper.insert(order);
                if (orderResult > 0) {
                    // 插入订单明细
                    for (OrderItem item : orderItems) {
                        item.setOrderId(order.getOrderId());
                    }
                    itemMapper.insertBatch(orderItems);
                    
                    // 扣减库存（在同一事务中使用同一个SqlSession）
                    for (Cart cart : merchantCarts) {
                        Product product = productMap.get(cart.getProductId());
                        product.setStock(product.getStock() - cart.getQuantity());
                        productMapper.update(product);
                    }
                    
                    // 删除购物车项
                    for (Cart cart : merchantCarts) {
                        cartMapper.delete(cart.getCartId());
                    }
                    
                    orderNos.add(orderNo);
                }
            }
            
            if (orderNos.isEmpty()) {
                sqlSession.rollback();
                // 回退余额（如果订单创建失败）
                userService.rechargeBalance(userId, totalAmount);
                return false;
            }
            
            sqlSession.commit();
            return true;
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            // 回退余额（如果发生异常）
            try {
                UserService userService = new UserServiceImpl();
                BigDecimal totalAmount = BigDecimal.ZERO;
                // 重新计算总金额
                CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
                ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
                for (Long cartId : cartIds) {
                    Cart cart = cartMapper.selectById(cartId);
                    if (cart != null) {
                        Product product = productMapper.selectById(cart.getProductId());
                        if (product != null) {
                            BigDecimal subtotal = product.getPrice().multiply(new BigDecimal(cart.getQuantity()));
                            totalAmount = totalAmount.add(subtotal);
                        }
                    }
                }
                userService.rechargeBalance(userId, totalAmount);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return false;
        } finally {
            sqlSession.close();
        }
    }
}

